import 'package:ebook/chapter.dart';
import 'package:ebook/components/Cell.dart';
import 'package:flutter/material.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'dart:async';
import 'package:ebook/base/Util.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

class Store extends StatefulWidget {
  const Store({Key? key, required this.title}) : super(key: key);
  final String title;
  @override
  _StoreState createState() => _StoreState();
}

class _StoreState extends State<Store> {
  List<Map<dynamic, dynamic>> dataList = [];
  EasyRefreshController scroll_controller = EasyRefreshController(
      controlFinishLoad: true, controlFinishRefresh: true);
  @override
  void dispose() {
    scroll_controller.dispose();
    super.dispose();
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Timer(const Duration(milliseconds: 500), () {
      scroll_controller.callRefresh();
      // loadData();
    });
    // initData();
  }

  Future initData() async {
    // Get a location using getDatabasesPath
    var databasesPath = await getDatabasesPath();
    UtilLog(databasesPath);
    String path = join(databasesPath, 'demo.db');

    // Delete the database
    await deleteDatabase(path);
    // open the database
    Database database = await openDatabase(path, version: 1,
        onCreate: (Database db, int version) async {
      // When creating the db, create the table
      await db.execute(
          'CREATE TABLE IF NOT EXISTS Book (id INTEGER PRIMARY KEY, name TEXT, url TEXT)');
      await db.execute(
          'CREATE TABLE IF NOT EXISTS Chapter (id INTEGER PRIMARY KEY, bid INTEGER, text TEXT, title TEXT, url TEXT)');
      await db.execute(
          'CREATE TABLE IF NOT EXISTS Read (id INTEGER PRIMARY KEY, bid INTEGER, cid INTEGER, page INTEGER, total INTEGER, date TEXT)');
    });
    database.close();
  }

  Future loadData() async {
    var dic = {
      "api_key": "rRTbmn7izydQArRcjAug+m8FMDLlypgE4tsgvLB8Bw",
      "lang": "en",
      "course_type": 2 //考试，1专科
    };
    // dic["memb_key"] = widget.userInfo["memb_key"] ?? "";
    Util.dio("/app/", method: "get").then((value) {
      final result = value.toResult();
      if (result.item2) {
        setState(() {
          dataList = List.from(result.item1["result"]);
          // dataList1 =
          //     List.from(result.item1["result"]);
          // dataList2 =
          //     List.from(result.item1["container"]["completed_class_list"]);
          // SharedPreferences.getInstance().then((v1) {
          //   v1.setString("learning_progress",
          //       result.item1["container"]["learning_progress"].toString());
          //   v1.setString("order_history",
          //       result.item1["container"]["order_history"].toString());
          //   ShareHandle.shared.eventBus.fire(Util.linkChangedNotification);
          // });
        });
      } else {
        showAlert(result.item4);
      }
      scroll_controller.finishRefresh(
          result.item2 ? IndicatorResult.success : IndicatorResult.fail);
    }).catchError((error, stackTrace) {
      UtilLog(error.toString());
      UtilLog(stackTrace);
      scroll_controller.finishRefresh(IndicatorResult.fail);
    });
  }

  void gotoChapter(context, item) {
    // Navigator.of(context).push(Chapter(data: item));
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => Chapter(data: item)),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: EasyRefresh(
          onRefresh: loadData,
          controller: scroll_controller,
          child: ListView(
              children: dataList.isNotEmpty
                  ? dataList
                      .map((e) => TextButton(
                          onPressed: () => gotoChapter(context, e),
                          child: Cell(
                            title: e["name"].toString(),
                            islink: true,
                          )))
                      .toList()
                  : [const Text("暫時未有")]),
        ));
  }
}
